package com.heifeng.cloudshelf.utils;

import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class LocationUtils {
    private static final String TAG = "LocationUtils";

    /**
     * http://ip-api.com/json/58.192.32.1?fields=520191&lang=en
     * 根据ip获取位置信息
     *
     * @param ip
     * @return {"accuracy":50,"as":"AS4538 China Education and Research Network Center",
     * "city":"Nanjing","country":"China","countryCode":"CN","isp":
     * "China Education and Research Network Center","lat":32.0617,"lon":118.7778,"mobile":false,
     * "org":"China Education and Research Network Center","proxy":false,"query":"58.192.32.1",
     * "region":"JS","regionName":"Jiangsu","status":"success","timezone":"Asia/Shanghai","zip":""}
     */
    public static String Ip2Location(String ip) {

        String urlStr = "http://ip-api.com/json/" + ip + "?fields=520191&lang=en";
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setReadTimeout(5000);//读取超时
            urlConnection.setConnectTimeout(5000); // 连接超时
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                //找到服务器的情况下,可能还会找到别的网站返回html格式的数据
                InputStream is = urlConnection.getInputStream();

                BufferedReader buff = new BufferedReader(new InputStreamReader(is, "UTF-8"));//注意编码，会出现乱码
                StringBuilder builder = new StringBuilder();
                String line = null;
                while ((line = buff.readLine()) != null) {
                    builder.append(line);
                }
                buff.close();//内部会关闭InputStream
                urlConnection.disconnect();

                String res = builder.toString();

                Log.e(TAG, "Ip2Location: res -- " + res);
                return res;
//                if (TextUtils.isJSONString(res)){
//                jsonObject = new JSONObject(res);
//
//                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 根据ip通过百度api去获取城市
     *
     * @param ip
     * @return
     */
    public static String Ip2LocationByBaiduApi(String ip) {
        try {
            String urls = "http://api.map.baidu.com/location/ip?ip=" + ip + "&ak=CvMDWgVnMyoa22gKiYQgDAXCeY1GmG7G&coor=bd09ll";
            URL url = new URL(urls);
            URLConnection connection = url.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = null;
            StringBuffer res = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                res.append(line);
            }
            reader.close();
            String ipAddr = res.toString();
            Log.e(TAG, "ip:" + ipAddr);
            return ipAddr;
//            if (StringUtils.isJSONString(ipAddr)){
//                JSONObject jsonObject = new JSONObject(ipAddr);
//                if ("1".equals(jsonObject.get("ret").toString())){
//                    return jsonObject.get("city").toString();
//                }else {
//                    return "读取失败";
//                }
//
//            }else {
//                return "访问后得到的不是json数据, res -- "+ipAddr;
//            }
        } catch (Exception e) {
            e.printStackTrace();
            return "读取失败 e -- " + e.getMessage();
        }
    }

    public static String getIp() {
        HttpURLConnection urlConnection = null;
        String ip = "";
        try {
            URL url = new URL("http://www.net.cn/static/customercare/yourip.asp");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            Scanner scanner = new Scanner(in).useDelimiter("\\A");
            String result = scanner.hasNext() ? scanner.next() : "";
            if (!result.isEmpty()) {
                if (result.indexOf("<h2>") > 0) {
                    ip = result.substring(result.indexOf("<h2>") + 4, result.indexOf("</h2>"));
                }
//                Log.e("TAG", "re:" + result);
//                Toast.makeText(this,result,Toast.LENGTH_SHORT).show();
//                ip = JSON.parseObject(result).getString("ip");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            urlConnection.disconnect();
            return ip;
        }
    }


    /**
     * 同步GET请求
     * new OkHttpClient;
     * 构造Request对象；
     * 通过前两步中的对象构建Call对象；
     * 在子线程中通过Call#execute()方法来提交同步请求；
     */
    public static void synchronizedGetRequests(String url,OnMessageCallBack onMessageCallBack) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求
                .build();
        final Call call = okHttpClient.newCall(request);
        new Thread(() -> {
            try {
                //直接execute call
                Response response = call.execute();
                String result = response.body().string();
                if (null != onMessageCallBack) {
                    onMessageCallBack.onMessage(result);
                }
            } catch (IOException e) {
                if (null != onMessageCallBack) {
                    onMessageCallBack.onError();
                }
                e.printStackTrace();
            }
        }).start();
    }

    public interface OnMessageCallBack{
        void onMessage(String message);
        void onError();
    }
}
